<?php
namespace app\common;

class Log
{
    protected static $logId = '';//全局LogId

    public static function write($content, $filename = 'debug.log', $dir = '')
    {
        $logId = uniqid();
        $content = is_array($content) ? json_encode($content) : $content;

        $dir = storage_path('logs/') . '/' . $dir;
        self::createDir($dir);
        if (empty(pathinfo($filename, PATHINFO_EXTENSION))) {
            $filename = $filename . '.log';
        }
        $fileNamePre = substr($filename, 0, strrpos($filename, "."));
        $fileNamePre = $fileNamePre . "-" . date('Ymd');
        $fileRealName = $fileNamePre . substr($filename, strrpos($filename, "."));
        $file = rtrim($dir, '/') . '/' . $fileRealName;
        if (!file_exists($file)) {
            @file_put_contents($file, '---------------创建---------------------'.PHP_EOL);
            @chmod($file, 0777);
        }
        error_log(date('Y-m-d H:i:s') . ' -- LogId:' . $logId . ' -- ' . $content . PHP_EOL, 3, $file);
        return true;
    }

    /**
     * 创建目录
     * @param string $dir 目录名
     * @return bool
     */
    private static function createDir($dir)
    {
        return is_dir($dir) or (self::createDir(dirname($dir)) and @mkdir($dir, 0777));
    }
}
